package com.sc.userspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.userspringboot.pojo.Games;
import com.sc.userspringboot.pojo.UserGames;
import com.sc.userspringboot.service.IGamesService;
import com.sc.userspringboot.service.IUserGamesService;
import com.sc.userspringboot.utils.ResponseMsg;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户关注游戏关联表 前端控制器
 * </p>
 *
 * @author user
 * @since 2025-09-19 06:25:46
 */
@RestController
@RequestMapping("/userGames")
public class UserGamesController {
    @Autowired
    private IUserGamesService userGamesService;
    @Autowired
    private IGamesService gamesService;
    
    @Value("${jwt.secret-key}")
    private String JWT_KEY;
    
    // 生成加密后的秘钥 secretKey
    private SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    
    @GetMapping("/getUserGames")
    public ResponseMsg getUserGames(Integer userId) {
        QueryWrapper<UserGames> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<UserGames> userGames = userGamesService.list(wrapper);
        List<Integer> gamesIds = userGames.stream()
                .map(UserGames::getGameId)
                .collect(Collectors.toList());
        if(gamesIds.size() == 0){
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", new ArrayList<>());
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", gamesService.getGames(gamesIds));
    }
    
    /**
     * 检查游戏是否已关注
     * @param gameId 游戏ID
     * @param request HTTP请求对象，用于获取token
     * @return 检查结果
     */
    @GetMapping("/checkGame")
    public ResponseMsg checkGame(@RequestParam Integer gameId, HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("isAdded", false);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "未登录", result);
        }
        
        try {
            // 使用JwtUtils解析token获取用户信息
            SecretKey key = generalKey();
            Claims claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
            
            // 从token中获取用户ID
            com.alibaba.fastjson.JSONObject userData = com.alibaba.fastjson.JSON.parseObject(claims.getSubject());
            Integer userId = userData.getInteger("userId");
            
            // 检查该游戏是否已经关注
            QueryWrapper<UserGames> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).eq("game_id", gameId);
            boolean isAdded = userGamesService.count(queryWrapper) > 0;
            
            Map<String, Object> result = new HashMap<>();
            result.put("isAdded", isAdded);
            
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("isAdded", false);
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "查询失败: " + e.getMessage(), result);
        }
    }
    
    /**
     * 关注游戏
     * @param requestParams 请求参数，包含游戏ID
     * @param request HTTP请求对象，用于获取token
     * @return 关注结果
     */
    @PostMapping("/addUserGame")
    public ResponseMsg followGame(@RequestBody Map<String, Object> requestParams, HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "未提供认证token");
        }
        
        try {
            // 获取请求参数中的游戏ID
            Integer gameId = (Integer) requestParams.get("gameId");
            if (gameId == null) {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "游戏ID不能为空");
            }
            
            // 解析token获取用户信息
            SecretKey key = generalKey();
            Claims claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
            
            // 从token中获取用户ID
            com.alibaba.fastjson.JSONObject userData = com.alibaba.fastjson.JSON.parseObject(claims.getSubject());
            Integer userId = userData.getInteger("userId");
            
            // 检查是否已经关注该游戏
            QueryWrapper<UserGames> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).eq("game_id", gameId);
            if (userGamesService.count(queryWrapper) > 0) {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "已关注该游戏");
            }
            
            // 创建用户游戏关联记录
            UserGames userGame = new UserGames();
            userGame.setUserId(userId);
            userGame.setGameId(gameId);
            userGame.setAddTime(new Date());
            
            // 保存到数据库
            boolean saved = userGamesService.save(userGame);
            if (saved) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "成功关注游戏");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "关注失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "token解析失败或关注失败: " + e.getMessage());
        }
    }
}